package com.chinanet.repository.extended;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 创建一个Repository 工厂类
 * https://docs.spring.io/spring-data/jpa/docs/2.0.10.RELEASE/reference/html/
 *
  */
public class ExtendedQuerydslJpaRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    public ExtendedQuerydslJpaRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }
    protected RepositoryFactorySupport createRepositoryFactory(final EntityManager entityManager){
        return new ExtendedQuerydslJpaRepositoryFactory(entityManager);
    }
    private static class ExtendedQuerydslJpaRepositoryFactory<T,I extends Serializable> extends JpaRepositoryFactory {
        private EntityManager entityManager;

        public ExtendedQuerydslJpaRepositoryFactory(EntityManager entityManager){
            super(entityManager);
            this.entityManager=entityManager;
        }
        protected Object getTargetRepository(RepositoryMetadata metadata){
            return new ExtendedQuerydslJpaRepositoryImpl<>(getEntityInformation(metadata.getDomainType()),entityManager);
        }
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata){
            return ExtendedQuerydslJpaRepositoryImpl.class;
        }
    }
}
